import React from 'react'
import { Button, Select, Form, Input } from 'antd'
import { useAppDispatch } from '@/store'
import { set_exam_list_data } from '@/store/slice/subject'
import { get_exam_list_async } from '@/store/slice/subject/request'
import useThrottle from '@/hooks/useThrottle'

type FieldType = {
  user_name: string
  judge: boolean | string
}

// 搜索组件
export default function Search() {
  const dispatch = useAppDispatch()

  // 优化查找参数，把值undefind转换为""
  const formatSearch = (values: FieldType) => {
    const newValues = { ...values }
    if (typeof values.judge === 'undefined') {
      newValues.judge = ''
    }

    if (typeof values.user_name === 'undefined') {
      newValues.user_name = ''
    }

    return newValues
  }

  const onFinish = (values: FieldType) => {
    const search_value = formatSearch(values)
    //修改查找参数和现在的页数
    dispatch(
      set_exam_list_data({
        search_params: search_value,
        current_page: 1
      })
    )

    // 根据参数查询
    dispatch(
      get_exam_list_async({
        ...search_value,
        pageSize: 6,
        pageNo: 1
      })
    )
  }

  return (
    <div>
      <Form layout="inline" name="basic" style={{ maxWidth: 600 }} onFinish={useThrottle(onFinish, 2000)} autoComplete="off">
        <Form.Item<FieldType> label="花名:" name="user_name">
          <Input />
        </Form.Item>

        <Form.Item<FieldType> label="是否阅卷" name="judge">
          <Select
            style={{ width: 120 }}
            options={[
              { value: true, label: '是' },
              { value: false, label: '否' }
            ]}
          />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit">
            查询
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}
